package com.junsom;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

/**
 * Created by hejunsong on 2016-9-2.
 */
public class StreamDemo {

    /**
     * 串行排序
     */
   public static void sortSequential() {
        List<String> list = new ArrayList<String>();
        for(int i=0;i<1000000;i++){
            double d = Math.random()*1000;
            list.add(d+"");
        }
        long start = System.nanoTime();//获取系统开始排序的时间点
        int count= (int) ((Stream) list.stream().sequential()).sorted().count();
        long end = System.nanoTime();//获取系统结束排序的时间点
        long ms = TimeUnit.NANOSECONDS.toMillis(end-start);//得到串行排序所用的时间

        System.out.println(ms+"ms");
    }

    /**
     * 并行排序
     */
    public static void sortParallel() {
        List<String> list = new ArrayList<String>();
        for(int i=0;i<1000000;i++){
            double d = Math.random()*1000;
            list.add(d+"");
        }
        long start = System.nanoTime();//获取系统开始排序的时间点
        int count = (int)((Stream) list.stream().parallel()).sorted().count();
        long end = System.nanoTime();//获取系统结束排序的时间点
        long ms = TimeUnit.NANOSECONDS.toMillis(end-start);//得到并行排序所用的时间
        System.out.println(ms+"ms");
    }

    public static void streamFilter() {
        List<String> list = new ArrayList<String>();
        for(int i=0;i<1000;i++){
            double d = Math.random()*1000;
            list.add(d+"");
        }
        list.stream().filter((s) -> s.startsWith("1")).forEach(System.out::println);
        System.out.println("filter-forEach 结束");

        String[] strs = list.stream().sorted().toArray(String[]::new);
        System.out.println("sorted-toArray 结束. strs=" + strs);

        Object f = list.stream().map((String s) -> {
            System.out.println(s);
            return s;
        }).findFirst();
        System.out.println("map-findFirst 结束. f=" + f);

        Boolean bln = list.stream().distinct().anyMatch(s -> {
            if (s.equals("123")) {
                return true;
            } else {
                return false;
            }
        });
        System.out.println("distinct-anyMatch 结束. bln=" + bln);

        list.stream().limit(900000).skip(100).forEach(System.out::println);
        System.out.println("limit-skip-forEach 结束.");
    }
}
